﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using CoreEx.Database.Linq.Translators;
using CoreEx.Database.Query.Expressions;
using LinFu.IoC.Configuration;

namespace CoreEx.Database.Linq.Implementation.Translators
{
    [Implements(typeof(IExpressionTranslator_generic<MethodCallExpression>), ServiceName = "get_Length")]
    [Implements(typeof(IExpressionTranslator_generic<MethodCallExpression>), ServiceName = "ToString")]
    public class StringMethodCallExpressionTranslator : MethodCallExpressionTranslatorGeneric
    {
        public StringMethodCallExpressionTranslator(TranslateResult translateResult) : base(translateResult) {}

        public override DbExpression Translate(MethodCallExpression expression)
        {
            var methodName = expression.Method.Name;

            if (methodName == "get_Length")
                return HandleGetLength(expression);

            if (methodName == "ToString")
                return HandleToString(expression);

            throw new NotSupportedException(string.Format("The method '{0}' is not supported",methodName));
        }

        private DbExpression HandleGetLength(MethodCallExpression methodCallExpression)
        {
            var dbExpression = ExpressionFactory.Length(Visit(methodCallExpression.Object));
            return dbExpression;
        }

        private DbExpression HandleToString(MethodCallExpression methodCallExpression)
        {
            var dbExpression = ExpressionFactory.Cast(Visit(methodCallExpression.Object), typeof (string));
            return dbExpression;
        }

    }
}
